<template>
  <div class="tinymce-editor-main">
    <Editor
      v-model="myValue"
      :init="init"
      :disabled="disabled"
      :placeholder="placeholder"
      :id="tinymceId"
      class="tinymce-editor"
    ></Editor>
  </div>
</template>
<script setup lang="ts">
  import { onBeforeMount, reactive, ref, onMounted, defineEmits, watch } from "vue";
  // import { upload } from "@/api/uploads"; // 自定义上传方法
  import Editor from "@tinymce/tinymce-vue";
  import tinymce from "tinymce/tinymce";
  import "tinymce/themes/silver";
  import "tinymce/themes/silver/theme";
  // import "tinymce/models/dom";
  import "tinymce/icons/default";
  import "tinymce/icons/default/icons";
  // 引入编辑器插件
  import "tinymce/plugins/code"; //编辑源码
  import "tinymce/plugins/image"; //插入编辑图片
  // import "tinymce/plugins/media"; //插入视频
  // import "tinymce/plugins/link"; //超链接
  import "tinymce/plugins/preview"; //预览
  import "tinymce/plugins/template"; //模板
  import "tinymce/plugins/table"; //表格
  import "tinymce/plugins/pagebreak"; //分页
  import "tinymce/plugins/lists"; //列
  import "tinymce/plugins/advlist"; //列
  import "tinymce/plugins/quickbars"; //快速工具条
  import "tinymce/plugins/wordcount"; // 字数统计插件
  // import "@/assets/tinymce/langs/zh-Hans.js"; //下载后的语言包
  import "tinymce/skins/content/default/content.css";
  // import "./plugin/ai-smart.js";
  const emits = defineEmits(["update:value"]);
  onBeforeMount(() => {
    tinymce.baseURL = "tinymce";
  });

  const props = defineProps({
    value: {
      type: String,
      default: "",
    },
    placeholder: {
      type: String,
      default: "在这里输入文字",
    },
    height: {
      type: Number,
      default: 500,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    plugins: {
      type: [String, Array],
      default:
        "code    preview table   pagebreak lists advlist fileman  custom_plugin textpattern  markdown",
    },
    toolbar: {
      type: [String, Array],
      default:
        "undo redo codesample bold italic underline strikethrough  alignleft aligncenter alignright alignjustify \
        bullist numlist outdent indent removeformat forecolor backcolor |formatselect fontselect fontsizeselect | \
        blocks fontfamily fontsize pagebreak lists   table  preview | code selectall  custom_button",
    },
    templates: {
      type: Array,
      default: () => [],
    },
    options: {
      type: Object,
      default: () => {},
    },
  });
  //用于接收外部传递进来的富文本
  const myValue = ref(props.value);
  const tinymceId = ref(
    "vue-tinymce-" + +new Date() + ((Math.random() * 1000).toFixed(0) + "")
  );

  const init = reactive({
    selector: "#" + tinymceId.value, //富文本编辑器的id,
    language_url: "/tinymce/langs/zh_CN.js", // 语言包的路径，具体路径看自己的项目，文档后面附上中文js文件
    language: "zh_CN", //语言
    skin_url: "/tinymce/skins/ui/oxide", // skin路径，具体路径看自己的项目
    content_css: "/tinymce/skins/content/default/content.css",
    content_style: "img {max-width:100%;}",
    menubar: false, //顶部菜单栏显示
    statusbar: false, // 底部的状态栏
    contextmenu: "bold copy  cut fileman markdown",
    contextmenu_avoid_overlap: ".mce-spelling-word", // 避免弹出菜单重叠
    plugins: props.plugins,
    // toolbar: props.toolbar,
    toolbar: false, // 隐藏工具栏
    inline: true,
    toolbar_mode: "sliding",
    font_formats:
      "Arial=arial,helvetica,sans-serif; 宋体=SimSun; 微软雅黑=Microsoft Yahei; Impact=impact,chicago;", //字体
    paste_convert_word_fake_lists: false, // 插入word文档需要该属性
    font_size_formats: "12px 14px 16px 18px 22px 24px 36px 72px", //文字大小
    height: props.height, //编辑器高度
    placeholder: props.placeholder,
    branding: false, //是否禁用“Powered by TinyMCE”
    image_dimensions: false, //去除宽高属性
    paste_webkit_styles: "all",
    paste_merge_formats: true,
    nonbreaking_force_tab: false,
    paste_auto_cleanup_on_paste: false,
    file_picker_types: "file",
    resize: true,
    elementpath: true,
    templates: props.templates,
    image_caption: true,
    image_advtab: true,
    convert_urls: false,
    textpattern_patterns: [
      { start: "*", end: "*", format: "italic" },
      { start: "**", end: "**", format: "bold" },
      { start: "#", format: "h1" },
      { start: "##", format: "h2" },
      { start: "###", format: "h3" },
      { start: "####", format: "h4" },
      { start: "#####", format: "h5" },
      { start: "######", format: "h6" },
      { start: "1. ", cmd: "InsertOrderedList" },
      { start: "* ", cmd: "InsertUnorderedList" },
      { start: "- ", cmd: "InsertUnorderedList" },
      { start: "\n", replacement: "<br/>" },
      { start: "---", replacement: "<hr/>" },
      { start: "--", replacement: "—" },
      { start: "-", replacement: "—" },
      { start: "(c)", replacement: "©" },
      { start: "//brb", replacement: "Be Right Back" },
      {
        start: "//heading",
        replacement:
          '<h1 style="color:blue">Heading here</h1><p><em>Date: 01/01/2000</em></p> ',
      },
    ],
    images_upload_handler: function (blobInfo, progress) {
      console.log(blobInfo, progress);
      // return new Promise((resolve, reject) => {
      //   const data = new FormData();
      //   data.append("file", blobInfo.blob(), blobInfo.filename());
      // update(data)
      //   .then((res) => {
      //     resolve(res.data.src);
      //   })
      //   .catch(() => {
      //     reject("Image upload failed");
      //   });
      // });
    },
    // 文件上传
    // file_picker_callback: (callback, value, meta) => {
    //   // Provide file and text for the link dialog
    //   if (meta.filetype == "file") {
    //     callback("mypage.html", { text: "My text" });
    //   }
    //   // Provide image and alt text for the image dialog
    //   if (meta.filetype == "image") {
    //     callback("myimage.jpg", { alt: "My alt text" });
    //   }
    //   // Provide alternative source and posted for the media dialog
    //   if (meta.filetype == "media") {
    //     callback("movie.mp4", { source2: "alt.ogg", poster: "image.jpg" });
    //   }
    // },
    setup: function (editor) {
      editor.on("init", function () {
        this.getBody().style.fontSize = "14px";
      });
      editor.on("contextmenu", function (editor) {
        // this.settings.contextmenu = "fileman | bold copy  cut defendImage";
        debugger;

        // var exampleMenuItem = this.menuItems["italic"];
        // this.menuItems["fileman"] = exampleMenuItem;

        // this.menuItems["fileman"].cmd = "mceFileMan";
        // this.menuItems["fileman"].icon = "../../file-icon.png";
        // this.menuItems["fileman"].text = "File Manager";
      });
      editor.on("OpenWindow", function (e) {
        //FIX 编辑器在el-drawer中，编辑器的弹框无法获得焦点
        var D = document.querySelector(".el-drawer.open");
        var E = e.target.editorContainer;
        if (D && D.contains(E)) {
          var nowDA = document.activeElement;
          setTimeout(() => {
            document.activeElement.blur();
            nowDA.focus();
          }, 0);
        }
      });
    },
    ...props.options,
  });
  //监听外部传递进来的的数据变化
  watch(
    () => props.value,
    () => {
      myValue.value = props.value;
      emits("update:value", myValue.value);
    }
  );
  //监听富文本中的数据变化
  watch(
    () => myValue.value,
    () => {
      emits("update:value", myValue.value);
    }
  );
  //在onMounted中初始化编辑器
  onMounted(() => {
    tinymce.init({});
  });
</script>
<style>
  .tinymce-editor-main {
    width: 100%;
    height: 100%;
    border: solid 1px pink;
  }

  .tinymce-editor {
    min-height: 100px;
    border: solid 1px gray;
  }
</style>
